#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
离线海图下载工具启动脚本
"""

import os
import sys
import webbrowser
import subprocess
import time
import platform

def check_dependencies():
    """
    检查依赖是否安装
    """
    try:
        import flask
        import requests
        import PIL
        import tqdm
        import flask_cors
        return True
    except ImportError as e:
        print(f"缺少依赖: {str(e)}")
        return False

def install_dependencies():
    """
    安装依赖
    """
    current_dir = os.path.dirname(os.path.abspath(__file__))
    requirements_file = os.path.join(current_dir, "backend", "requirements.txt")
    
    if not os.path.exists(requirements_file):
        print(f"错误: 找不到依赖文件 {requirements_file}")
        return False
    
    print("正在安装依赖...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", requirements_file])
        print("依赖安装完成")
        return True
    except subprocess.CalledProcessError as e:
        print(f"依赖安装失败: {str(e)}")
        return False

def main():
    """
    主函数，启动应用程序
    """
    # 获取当前目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    backend_dir = os.path.join(current_dir, "backend")
    
    # 检查后端目录是否存在
    if not os.path.exists(backend_dir):
        print("错误: 找不到后端目录")
        return 1
    
    # 检查依赖
    if not check_dependencies():
        print("尝试安装依赖...")
        if not install_dependencies():
            print("依赖安装失败，请手动安装依赖:")
            print(f"pip install -r {os.path.join('backend', 'requirements.txt')}")
            return 1
    
    # 创建必要的目录结构
    data_dir = os.path.join(current_dir, "data")
    mbtiles_dir = os.path.join(data_dir, "mbtiles")
    tiles_dir = os.path.join(data_dir, "tiles")
    
    for directory in [data_dir, mbtiles_dir, tiles_dir]:
        if not os.path.exists(directory):
            os.makedirs(directory)
    
    # 启动Flask应用
    print("启动离线海图下载工具...")
    
    # 使用Python解释器启动应用
    app_script = os.path.join(backend_dir, "app.py")
    
    try:
        # 在新进程中启动应用
        if platform.system() == "Windows":
            process = subprocess.Popen([sys.executable, app_script], 
                                      cwd=backend_dir,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE,
                                      shell=True,
                                      creationflags=subprocess.CREATE_NO_WINDOW)
        else:
            process = subprocess.Popen([sys.executable, app_script], 
                                      cwd=backend_dir,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
        
        # 等待服务器启动
        time.sleep(2)
        
        # 打开浏览器
        webbrowser.open('http://localhost:5000')
        
        print("应用已启动，请在浏览器中访问: http://localhost:5000")
        print("按Ctrl+C停止服务器...")
        
        # 等待进程结束
        process.wait()
        
    except KeyboardInterrupt:
        print("\n正在停止服务器...")
        process.terminate()
        print("服务器已停止")
    except Exception as e:
        print(f"错误: {str(e)}")
        return 1
    
    return 0

if __name__ == "__main__":
    sys.exit(main()) 